package info.demo.acao;

import info.demo.entity.Conta;
import info.demo.entity.Page;
import info.demo.service.ContaService;
import info.demo.view.BufferedResponseWrapper;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.springframework.web.struts.DispatchActionSupport;

public class CarregarInicial extends DispatchActionSupport {
	
	public ActionForward carregar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		carregarGrupos(mapping, form, request, response);
		return mapping.findForward("lista");
	}
	
	public ActionForward menu(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		return mapping.findForward("cfcweb");
	}

	public ActionForward janelamultiplascontas(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		carregarGrupos(mapping, form, request, response);
		return mapping.findForward("multiplascontas");
	}

	public ActionForward janelanovaconta(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		carregarGrupos(mapping, form, request, response);
		request.setAttribute("acao", "Nova conta");
		return mapping.findForward("inserirconta");
	}

	public ActionForward removerconta(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer idconta = Integer.parseInt(request.getParameter("conta"));
		ContaService contaService = (ContaService)getWebApplicationContext().getBean("contaService");
		Conta conta = contaService.recuperaContaPorId(idconta);
		if (conta==null) {
			ActionMessage mensagem = new ActionMessage("msg.remover.conta.nao.encontrada");
			ActionMessages messages = new ActionMessages();
			messages.add(ActionMessages.GLOBAL_MESSAGE, mensagem);
			saveErrors(request, messages);
			return mapping.findForward("fracasso");
		} else {
			contaService.delete(conta);
			ActionMessage mensagem = new ActionMessage("msg.remover.conta.sucesso");
			ActionMessages messages = new ActionMessages();
			messages.add(ActionMessages.GLOBAL_MESSAGE, mensagem);
			saveMessages(request, messages);
			return mapping.findForward("sucesso");
		}
	}

	public ActionForward pagarconta(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer idconta = Integer.parseInt(request.getParameter("conta"));
		ContaService contaService = (ContaService)getWebApplicationContext().getBean("contaService");
		Conta conta = contaService.recuperaContaPorId(idconta);
		if (conta==null) {
			ActionMessage mensagem = new ActionMessage("msg.pagar.conta.nao.encontrada");
			ActionMessages messages = new ActionMessages();
			messages.add(ActionMessages.GLOBAL_MESSAGE, mensagem);
			saveErrors(request, messages);
			return mapping.findForward("fracasso");
		} else {
			conta.setDataPaga(new Date());
			conta.setPaga(true);
			contaService.saveOrUpdate(conta);
			ActionMessage mensagem = new ActionMessage("msg.pagar.conta.sucesso");
			ActionMessages messages = new ActionMessages();
			messages.add(ActionMessages.GLOBAL_MESSAGE, mensagem);
			saveMessages(request, messages);
			request.setAttribute("detalheConta",conta);
			return mapping.findForward("detalhe");
		}
	}
	
	public ActionForward inserirConta(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Conta entidade = ContaForm.montaEntidade(mapping, form, request, response);
		ContaService contaService = (ContaService)getWebApplicationContext().getBean("contaService");
		contaService.saveOrUpdate(entidade);
		ActionMessage mensagem = new ActionMessage("msg.inserir.conta.sucesso");
		ActionMessages messages = new ActionMessages();
		messages.add(ActionMessages.GLOBAL_MESSAGE, mensagem);
		saveMessages(request, messages);
		if ("novo".equalsIgnoreCase(request.getParameter("opcao"))) {
			carregarGrupos(mapping, form, request, response);
			request.setAttribute("acao", "Nova conta");
			return mapping.findForward("inserirconta");
		} else {
			request.setAttribute("detalheConta",entidade);
			return mapping.findForward("detalhe");
		}
	}
	
	public ActionForward inserirMultiplasContas(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Conta entidades[] = ContaForm.montaEntidadesMultiplas(mapping, form, request, response);
		ContaService contaService = (ContaService)getWebApplicationContext().getBean("contaService");
		for(Conta entidade : entidades) {
			contaService.saveOrUpdate(entidade);
		}
		ActionMessage mensagem = new ActionMessage("msg.inserir.multiplas.conta.sucesso");
		ActionMessages messages = new ActionMessages();
		messages.add(ActionMessages.GLOBAL_MESSAGE, mensagem);
		saveMessages(request, messages);
		return mapping.findForward("inseridoMultiplo");
	}
	
	public ActionForward atualizarConta(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ContaService contaService = (ContaService)getWebApplicationContext().getBean("contaService");
		Integer idConta = (Integer)((DynaActionForm)form).get("id");
		Conta entidade = contaService.getById(idConta);
		ContaForm.atualizarEntidade(entidade, mapping, form, request, response);
		contaService.update(entidade);
		ActionMessage mensagem = new ActionMessage("msg.atualizar.conta.sucesso");
		ActionMessages messages = new ActionMessages();
		messages.add(ActionMessages.GLOBAL_MESSAGE, mensagem);
		saveMessages(request, messages);
		request.setAttribute("detalheConta",entidade);
		return mapping.findForward("detalhe");
	}
	
	public ActionForward carregarConteudo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String pagina=request.getParameter("pagina");
        Integer atraso=0;
        try {
        	atraso=Integer.parseInt(request.getParameter("atraso"));
        } catch(Exception e) {
        	atraso=0;
        }
        long l1=System.currentTimeMillis();
        while(System.currentTimeMillis()-l1<(atraso*1000));
        return ajaxWrap("/jsp/"+pagina+".jsp", mapping, form, request, response);
	}
	
	public ActionForward listar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ContaService contaService = (ContaService)getWebApplicationContext().getBean("contaService");
		String colunaData = request.getParameter("colunaData");
		String dataInicio = request.getParameter("dataInicio");
		String dataFim = request.getParameter("dataFim");
		Page p = Page.definaMe(request);
		Date pDataInicio = null;
		Date pDataFim = null;
		SimpleDateFormat sdf=new SimpleDateFormat("dd/MM/yyyy");
		try {
			pDataInicio=sdf.parse(dataInicio);
			pDataFim=sdf.parse(dataFim);
		}catch(Throwable t) {
			pDataInicio=null;
			pDataFim=null;
		}
		
		request.setAttribute("contas",contaService.recuperaContas(ContaForm.montaPesquisa(request), p));
		request.setAttribute("pagina", p);
		return ajaxWrap("/jsp/tabela.jsp", mapping, form, request, response);
	}
	
	public ActionForward detalhar(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer idconta = Integer.parseInt(request.getParameter("conta"));
		ContaService contaService = (ContaService)getWebApplicationContext().getBean("contaService");
		request.setAttribute("detalheConta",contaService.recuperaContaPorId(idconta));
		return mapping.findForward("detalhe");
	}
	
	public ActionForward janelaeditarconta(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Integer idconta = Integer.parseInt(request.getParameter("conta"));
		ContaService contaService = (ContaService)getWebApplicationContext().getBean("contaService");
		request.setAttribute("detalheConta",contaService.recuperaContaPorId(idconta));
		carregarGrupos(mapping, form, request, response);
		request.setAttribute("acao", "Editar conta");
		return mapping.findForward("editarconta");
	}
	
	private void carregarGrupos(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		ContaService contaService = (ContaService)getWebApplicationContext().getBean("contaService");
		List<String> grupos = contaService.recuperaGruposContas();
		request.setAttribute("grupos", grupos);
	}
	
	private ActionForward ajaxWrap(String pagina,ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedResponseWrapper brw;
        RequestDispatcher rd = request.getRequestDispatcher(pagina);
        response.setContentType("text/html; charset=ISO-8859-1");
        response.setHeader("Cache-Control", "no-cache");
        rd.include(request, brw=new BufferedResponseWrapper(response,"ISO-8859-1"));
        PrintWriter pw = response.getWriter();
        pw.write(brw.getOutput());
        pw.close();
        return null;
	}
	
}
